import axios from "axios";
import {
  ElMessage
} from "element-plus";


let baseUrl = "http://127.0.0.1:8000/";
// 创建第一个axios实例 service
const service = axios.create({
  baseURL:baseUrl,
  timeout: 5000,
  withCredentials: true
});

// Request interceptors for service
service.interceptors.request.use(
  (config) => {
    return config;
  },
  (error) => {
    Promise.reject(error);
  }
);

// Response interceptors for service
service.interceptors.response.use(
  (response) => {
    if (response.status !== 200) {
      ElMessage({
        type: "error",
        message: "服务器忙,请稍后再试~",
      });
      return;
    }
    return response;
  },
  (error) => {
    // do something
    return Promise.reject(error);
  }
);

// 创建第二个axios实例 httpService

const httpService = axios.create({
  baseURL: baseUrl,
  timeout: 3000
});

// 添加请求和响应拦截器 for httpService
httpService.interceptors.request.use(function (config) {
  config.headers.AUTHORIZATION = window.sessionStorage.getItem('token');
  return config;
}, function (error) {
  return Promise.reject(error);
});

httpService.interceptors.response.use(function (response) {
  return response;
}, function (error) {
  return Promise.reject(error);
});

// 定义导出对象
const api = {
  get: (url, params = {}) => {
    return new Promise((resolve, reject) => {
      httpService({
        url: url,
        method: 'get',
        params: params
      }).then(response => {
        resolve(response);
      }).catch(error => {
        reject(error);
      });
    });
  },
  post: (url, params = {}) => {
    return new Promise((resolve, reject) => {
      httpService({
        url: url,
        method: 'post',
        data: params
      }).then(response => {
        console.log(response)
        resolve(response);
      }).catch(error => {
        console.log(error)
        reject(error);
      });
    });
  },
  del: (url, params = {}) => {
    return new Promise((resolve, reject) => {
      httpService({
        url: url,
        method: 'delete',
        data: params
      }).then(response => {
        console.log(response)
        resolve(response);
      }).catch(error => {
        console.log(error)
        reject(error);
      });
    });
  },
  fileUpload: (url, params = {}) => {
    return new Promise((resolve, reject) => {
      httpService({
        url: url,
        method: 'post',
        data: params,
        headers: { 'Content-Type': 'multipart/form-data' }
      }).then(response => {
        resolve(response);
      }).catch(error => {
        reject(error);
      });
    });
  },
  getServerUrl: () => {
    return baseUrl;
  }
};

// 导出api对象
export {
  api
};

// 导出service实例作为默认导出
export default service;